<template>
  <div>
    <div class="app_card mb-2 pt-4 pb-4">
      <el-form class="search-form" :model="queryParam" label-width="90px" label-position="right">
        <el-row>
          <el-col :xs="8" :sm="8" :md="8" :lg="6" :xl="6">
            <el-form-item label="用户名">
              <el-input v-model="queryParam.UserName" placeholder="请输入用户名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="6" :xl="6">
            <el-form-item label="姓名">
              <el-input v-model="queryParam.RealName" placeholder="请输入姓名" clearable></el-input>
            </el-form-item> </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="12" :xl="12" class="t-r">
            <el-button type="primary" plain @click="onSearch(null)">搜索</el-button>
            <el-button type="primary" @click="onAdd()">添加</el-button>
            <el-button type="primary" plain @click="onDeleteMulti()">删除</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="app_card pt-4  pb-5">
      <el-table stripe size="large" :data="dataOfTable" height="calc(100vh - 320px)" sortable="custom" @sort-change="handleSortChange" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50" />
        <el-table-column prop="Id" label="ID" sortable> </el-table-column>
        <el-table-column prop="UserName" label="用户名" sortable>
        </el-table-column>
        <el-table-column prop="RealName" label="姓名" sortable> </el-table-column>
        <el-table-column prop="IsSuper" label="是否超级管理员" sortable>
          <template #default="scope">
            <el-switch size="large" v-model="scope.row.IsSuper" inline-prompt disabled active-value="1" inactive-value="0" active-text="是" inactive-text="否" />
          </template>
        </el-table-column>
        <el-table-column prop="UserType" label="管理员类型" sortable>
          <template #default="scope">
            <el-tag :type='scope.row.UserType ==1  ? "success"
            : scope.row.UserType == 2 ? "danger"
            : scope.row.UserType == 3 ? "warning"
            : ""' disable-transitions>{{findValue(userTypeOption,scope.row.UserType)}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Mobile" label="手机号" sortable> </el-table-column>
        <el-table-column prop="Status" label="状态" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.Status == 1 ? 'success' : 'danger'" disable-transitions>
              {{ scope.row.Status == 0 ? "禁用" : "启用" }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" @click="onEditRow(scope.row)">编辑
            </el-button>

          </template>
        </el-table-column>
      </el-table>
      <div class="mt-2">
        <el-pagination background v-model:currentPage="queryParam.page" v-model:page-size="queryParam.pageSize" :page-sizes="paginationOption.pageSizes" :background="false" :layout="paginationOption.layout" :total="paginationOption.total" @size-change="handleChangeSize" @current-change="handleChangeCurrent" />
      </div>

    </div>
    <edit-dialog ref="editDialogRef" @success="loadData()"></edit-dialog>
  </div>
</template>

<script setup>
/**
 * 管理员列表组件
 */
import { ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import useAuthStore from '@/stores/useAuthStore';
import { userTypeList } from '@/apis/model/UserModel';
import { findValue } from '@/utils/EsCommon';



//组件
import SearchPanel from './SearchPanel.vue';
import EditDialog from './EditDialog.vue';


console.log('[INFO] 创建管理员列表组件');
// ======================================================
//                      变量声明
// ======================================================

const authStore = useAuthStore();

const userTypeOption = ref(userTypeList);

// 组件引用
const editDialogRef = ref(null);
// 表格数据
const dataOfTable = ref([]);
// 组件可视状态
const visibleState = ref({
  searchPanel: true,
})
// 表格查询参数
const queryParam = ref({
  RealName: '',
  UserName: '',
  page: 1,
  pageSize: 10,
})
// 表格高级查询表单
const searchParam = ref({})
// 分页栏配置数据
const paginationOption = ref({
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: [10, 20, 50, 100, 500, 1000],
  total: 0,
})
// 表格多选数据
const multipleSelection = ref([]);

// ======================================================
//                      点击操作
// ======================================================


// 点击新增按钮
const onAdd = () => {
  editDialogRef.value.show(0, '添加用户');
}

// 批量编辑按钮
// const onEditMulti = () => {}

// 点击批量删除按钮
const onDeleteMulti = () => {
  let n = multipleSelection.value.length, ids = multipleSelection.value.map(v => v.Id).join();
  ElMessageBox.confirm(`确定要删除 ${n} 条记录吗？`, '警告').then(() => {
    EsAjax.post(ApiUrls.backenduserDelete, { param: { ids } }).then(res => {
      if (res.data.code !== 200) {
        ElMessage.warning(res.data.msg);
        return;
      }
      ElMessage.success('操作成功');
      loadData();
    }).catch(err => {
      ElMessage.error('网络错误：' + err.message);
    })
  }).catch(() => { })
}

// 点击快速搜索按钮
const onSearch = () => {
  queryParam.value.page = 1;
  loadData();
}
// 点击行内编辑按钮
const onEditRow = (row) => {
  editDialogRef.value.show(row.Id, '编辑 ' + row.UserName, row);
}

// ======================================================
//                      处理事件
// ======================================================

// 处理表格全选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 处理表格排序
const handleSortChange = (column) => {
  queryParam.value.orderby = column.prop + ' ' + (column.order == 'descending' ? 'desc' : 'asc');
  console.log(queryParam.value);
  loadData();
}

// 处理分页尺寸
const handleChangeSize = (val) => {
  console.log(`${val} items per page`);
  queryParam.value.page = 1;
  queryParam.value.pageSize = val;
  loadData();
}

// 处理页码
const handleChangeCurrent = (val) => {
  console.log(`current page: ${val}`)
  queryParam.value.page = val;
  loadData();
}

// ======================================================
//                      处理事件
// ======================================================

const loadData = () => {
  let params = Object.assign(queryParam.value, searchParam.value);
  console.log('发送搜索请求', params);
  EsAjax.post(ApiUrls.backenduserDatagrid, { params }).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    dataOfTable.value = res.data.data.data;
    paginationOption.value.total = res.data.data.total;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

loadData();
</script>

